# -*- coding:utf-8 -*-
import os
import urllib
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext, Context, loader
from django.conf import settings
from django.core.context_processors import csrf
from website.forms import UploadFileForm
from rise.xlsx import Xlsx

def index(request):
    """首页
    """
    links = [
        ('Call in & Walk in 信息统计', 'cw_list'),
    ]
    return render_to_response('index.html', {
            'links': links,
        })

def cw_list(request):
    """Call in & Walk in 文件列表
    """
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filename = request.FILES['file'].name
            filepathname = os.path.join(settings.XLSX_FILE_ROOT, filename)
            file = open(filepathname, 'a')
            for chunk in request.FILES['file'].chunks():
                file.write(chunk)
            file.close()
            # 跳转到统计页面
            return HttpResponseRedirect('/cw_fork/?fn=%s' % \
                        urllib.quote_plus(filename.encode('utf-8')))
    file_list = []
    fn_list = os.listdir(settings.XLSX_FILE_ROOT)
    for fn in fn_list:
        if fn.startswith('.'):
            continue
        fpn = os.path.join(settings.XLSX_FILE_ROOT, fn)
        fileinfo = {
            'name': fn,
            'st_mtime': os.stat(fpn).st_mtime,
            'ue_name': urllib.quote_plus(fn),
        }
        file_list.append(fileinfo)
    file_list.sort(key = lambda x: x['st_mtime'], reverse = True)
    form = UploadFileForm()
    c = {
            'file_list': file_list,
            'form':  form,
        }
    c.update(csrf(request))
    return render_to_response('cw_list.html', c)

def cw_fork(request):
    """Call in & Walk in 选择统计时间段
    """
    fn = request.REQUEST["fn"]
    fpn = os.path.join(settings.XLSX_FILE_ROOT, fn)
    xfile = Xlsx(fpn)
    c = {
        'filename': urllib.quote_plus(fn.encode('utf-8')),
        'months': [md[0] for md in xfile.monthdays],
        'weeks': xfile.weeks,
        'monthdays': xfile.monthdays,
    }
    return render_to_response('cw_fork.html', c)

def cw_stat(request):
    """统计
    """
    fn = request.REQUEST["fn"]
    by = request.REQUEST['by']
    key = request.REQUEST['key']
    field = request.REQUEST.get('field')
    # 获取时间段内的所有日期
    date_list = []
    if by == 'day':
        _date = datetime.datetime.strptime(key, '%Y-%m-%d')
        date_list.append(_date)
    elif by == 'week':
        _start, _end = [datetime.datetime.strptime(d, '%Y-%m-%d') for d in key.split("~")]
        while _start <= _end:
            date_list.append(_start)
            _start = _start + datetime.timedelta(days = 1)
    elif by == 'month':
        _date = datetime.datetime.strptime(key, '%Y-%m-%d')
        _month = _date.month
        while _date.month == _month:
            date_list.append(_date)
            _date = _date + datetime.timedelta(days = 1)
    # 获取时间段内的记录
    fpn = os.path.join(settings.XLSX_FILE_ROOT, fn)
    xfile = Xlsx(fpn)
    rows = [row for row in xfile.rows if row['date'] in date_list]

    # 过滤字段
    priority = ['电转咨询师', '关单咨询师', '当前状态', '咨询渠道', '咨询量来源 - 类型★', '咨询量来源 - 具体来源★', ]
    fvs = [{'field': f} for f in priority]
    for fv in fvs:
        fv['values'] = set()
        fv['fq'] = urllib.quote_plus(f)
        for row in rows:
            if row[fv['field']] is None:
                continue
            fv['values'].add(row[fv['field']])
    # 按字段值过滤
    condition = {}
    count = 0
    for f in priority:
        value = request.REQUEST.get(f.decode('utf-8'))
        if value is None or value == '0':
            continue
        condition[f] = value.encode('utf-8')
    if condition:
        for row in rows:
            flag = True
            for c, v in condition.items():
                if v != row[c].encode('utf-8'):
                    flag = False
                    break
            if flag:
                count += 1
    else:
        count = len(rows)

    c = {
        'fvs': fvs,
        'count': count,
        'condition': condition,

        'fn': fn,
        'by': by,
        'key': key,
    }
    return render_to_response('cw_stat.html', c)


